// Package qq QQ扩展包
package qq

import (
	m "ginmin/middleware"
	"io"
	"net/http"
	"net/url"
	"strings"
)

type QqPkg struct {
	AppId  string //appid
	Secret string //密钥
}

// Login 微信登录，返回url链接
func (pkg *QqPkg) Login(redirect_uri string) string {
	redirect_uri = url.QueryEscape(redirect_uri)
	appid := pkg.AppId
	return "https://graph.qq.com/oauth2.0/authorize?client_id=" + appid + "&response_type=code&redirect_uri=" + redirect_uri + "&state=B1h88SlhJ2"
}

// Auth 微信返回code，获取用户信息
func (pkg *QqPkg) Auth(code, redirect_uri string) map[string]string {
	appid := pkg.AppId
	secret := pkg.Secret
	redirect_uri = url.QueryEscape(redirect_uri)
	urls := "https://graph.qq.com/oauth2.0/token?client_id=" + appid + "&client_secret=" + secret + "&code=" + code + "&grant_type=authorization_code&redirect_uri=" + redirect_uri + "&fmt=json"
	resp, _ := http.Get(urls)
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil
	}
	jsondata := string(body)
	token := m.Json_decode_string(jsondata, "access_token")
	if token == "" {
		return nil
	}

	urls = "https://graph.qq.com/oauth2.0/me?access_token=" + token + "&unionid=1&fmt=json"
	resp2, _ := http.Get(urls)
	defer resp2.Body.Close()
	body2, err2 := io.ReadAll(resp2.Body)
	if err2 != nil {
		return nil
	}
	jsondata = string(body2)
	openid := m.Json_decode_string(jsondata, "openid")
	client_id := m.Json_decode_string(jsondata, "client_id")
	unionid := m.Json_decode_string(jsondata, "unionid")
	if openid == "" {
		return nil
	}

	urls = "https://graph.qq.com/user/get_user_info?access_token=" + token + "&oauth_consumer_key=" + client_id + "&openid=" + openid
	resp3, _ := http.Get(urls)
	defer resp3.Body.Close()
	body3, err3 := io.ReadAll(resp3.Body)
	if err3 != nil {
		return nil
	}
	jsondata = string(body3)
	jsonarray := m.Json_decode_array(jsondata)
	ret := m.Json_decode_int(jsondata, "ret")
	if ret != 0 {
		return nil
	}
	userInfo := map[string]string{
		"openid":     openid,
		"nickname":   jsonarray["nickname"],
		"sex":        jsonarray["gender"],
		"headimgurl": strings.Replace(jsonarray["figureurl_qq_2"], "http://", "https://", 1),
		"unionid":    unionid,
		"types":      "QQ",
	}
	return userInfo
}
